const express = require('express');
const app = express();
const cors = require('cors');
const fs = require('fs');

const PORT = 3030;
const allowedOrigins = [
  'http://localhost:8080',
  'http://localhost:3030'
];

const corsOptions = {
  origin: (origin, callback) => {
    if (!origin || allowedOrigins.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
};

app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

useController();
app.listen(PORT);


function useController() {
  const controllers = fs.readdirSync('./controller');
  controllers.forEach(c => {
    app.use(require('./controller/' + c));
  });
}

setInterval(() => {
  const time = new Date();
  const hour = time.getHours();
  const minute = time.getMinutes();
  const busy = require('./utils/getProcess');
  const state = busy();
  console.log(`${hour}:${minute}: ${state} memory used`);
  if(state > 80 || (hour == 7 && minute > 53 && minute < 60) || (hour == 13 && minute > 23 && minute < 30) || (hour == 19 && minute > 24 && minute < 30) || (hour == 23 && minute > 20 && minute < 30)) {
    process.send('restart');
    return
  }
}, 300000);